package com.gaoyang.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;

/**
 * Created by gaoyang on 2017/10/11.
 */
public class Chaojiying {
    //淘宝apikey ce3a1ff5a29e4040bf60038db247037e
    //http://www.chaojiying.com/price.html 这个页面看打码的类型
    private final static String url = "http://10.40.50.65/chaojiying_proxy/v2/processing";
    private final static String apikey = "8cbac7060ccf41fea0dad5eef3a03236";

    private final static OkHttpClient client = new OkHttpClient();
    private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");

    public static String getCaptcha(String base64){
        if(base64.startsWith("data:image/jpg;base64,")){
            base64 = base64.replace("data:image/jpg;base64,", "");
        }else{
            System.out.println("不支持打码类型");
        }
        try {
            JSONObject postJson = new JSONObject();
            postJson.put("file_base64", base64);
            postJson.put("codetype", 1008);
            postJson.put("domain", "10086.cn");
            RequestBody body = RequestBody.create(JSON_TYPE, postJson.toJSONString());
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("apikey", apikey)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();
            if(200 == response.code()){
                return JSON.parseObject(response.body().string()).getString("pic_str");
            }else{
                System.out.println("打码失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("请求打码失败");
        }
        return "";
    }

    public static String getCaptcha(String base64, String codetype){
        if(base64.startsWith("data:image/jpg;base64,")){
            base64 = base64.replace("data:image/jpg;base64,", "");
        }else{
            System.out.println("不支持打码类型");
        }
        try {
            JSONObject postJson = new JSONObject();
            postJson.put("file_base64", base64);
            postJson.put("codetype", codetype);
            postJson.put("domain", "dianping.com");
            RequestBody body = RequestBody.create(JSON_TYPE, postJson.toJSONString());
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("apikey", apikey)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();
            if(200 == response.code()){
                return JSON.parseObject(response.body().string()).getString("pic_str");
            }else{
                System.out.println("打码失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("请求打码失败");
        }
        return "";
    }


    /**
     * 识别图片_按图片二进制流
     * @param username		用户名
     * @param password		密码
     * @param softid		软件ID
     * @param codetype		图片类型
     * @param len_min		最小位数
     * @param byteArr		图片二进制数据流
     * @return
     * @throws IOException
     */
    public static String PostPic(String username, String password, String softid, String codetype, String len_min, byte[] byteArr) {
        String result = "";
        String param = String
                .format("user=%s&pass=%s&softid=%s&codetype=%s&len_min=%s", username, password, softid, codetype, len_min);
        try {
            result = Chaojiying.httpPostImage(param, byteArr);
        } catch(Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 识别图片_按图片文件路径
     * @param username		用户名
     * @param password		密码
     * @param softid		软件ID
     * @param codetype		图片类型
     * @param len_min		最小位数
     * @param filePath		图片文件路径
     * @return
     * @throws IOException
     */
    public static String PostPic(String username, String password, String softid, String codetype, String len_min, String filePath) {
        String result = "";
        String param = String
                .format(
                        "user=%s&pass=%s&softid=%s&codetype=%s&len_min=%s", username, password, softid, codetype, len_min);
        try {
            File f = new File(filePath);
            if (null != f) {
                int size = (int) f.length();
                byte[] data = new byte[size];
                FileInputStream fis = new FileInputStream(f);
                fis.read(data, 0, size);
                if(null != fis) fis.close();

                if (data.length > 0)
                    result = Chaojiying.httpPostImage(param, data);
            }
        } catch(Exception e) {
            e.printStackTrace();
        }


        return result;
    }

    /**
     * 字符串MD5加密
     * @param s 原始字符串
     * @return  加密后字符串
     */
    public final static String MD5(String s) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F' };
        try {
            byte[] btInput = s.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 核心上传函数
     * @param param			请求参数，如：username=test&password=1
     * @param data			图片二进制流
     * @return				response
     * @throws IOException
     */
    public static String httpPostImage(String param, byte[] data) throws IOException {
        long time = (new Date()).getTime();
        URL u = null;
        HttpURLConnection con = null;
        String boundary = "----------" + MD5(String.valueOf(time));
        String boundarybytesString = "\r\n--" + boundary + "\r\n";
        OutputStream out = null;

        u = new URL("http://upload.chaojiying.net/Upload/Processing.php");

        con = (HttpURLConnection) u.openConnection();
        con.setRequestMethod("POST");
        //con.setReadTimeout(60000);
        con.setConnectTimeout(12000);
        con.setReadTimeout(12000);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(true);
        con.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);

        out = con.getOutputStream();

        for (String paramValue : param.split("[&]")) {
            out.write(boundarybytesString.getBytes("UTF-8"));
            String paramString = "Content-Disposition: form-data; name=\""
                    + paramValue.split("[=]")[0] + "\"\r\n\r\n" + paramValue.split("[=]")[1];
            out.write(paramString.getBytes("UTF-8"));
        }
        out.write(boundarybytesString.getBytes("UTF-8"));

        String paramString = "Content-Disposition: form-data; name=\"userfile\"; filename=\""
                + "chaojiying_java.gif" + "\"\r\nContent-Type: application/octet-stream\r\n\r\n";
        out.write(paramString.getBytes("UTF-8"));

        out.write(data);

        String tailer = "\r\n--" + boundary + "--\r\n";
        out.write(tailer.getBytes("UTF-8"));

        out.flush();
        out.close();

        StringBuffer buffer = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(con
                .getInputStream(), "UTF-8"));
        String temp;
        while ((temp = br.readLine()) != null) {
            buffer.append(temp);
            buffer.append("\n");
        }

        return buffer.toString();
    }

//    public static String processing(String base64) {
//        Map<String, String> paramMap = new HashMap<String, String>();
//        paramMap.put("user", "gaoyang821112");
//        paramMap.put("pass", "4433221");
//        paramMap.put("softid", "893913");
//        paramMap.put("codetype", "1004");
//        paramMap.put("len_min", "4");
//        paramMap.put("file_base64", base64);
//
//        StringBuffer strbuffer = new StringBuffer();
//        String paramUrl = "";
//        if ((paramMap != null) && (paramMap.size() > 0)) {
//            for (Map.Entry entry : paramMap.entrySet()) {
//                String key = String.valueOf(entry.getKey());
//                String value = String.valueOf(entry.getValue());
//                strbuffer.append(key);
//                strbuffer.append("=");
//                strbuffer.append(value);
//                strbuffer.append("&");
//
//            }
//            paramUrl = strbuffer.toString();
//            paramUrl = paramUrl.substring(0, paramUrl.length() - 1);
//        }
//
//        HttpURLConnection connection = null;
//        StringBuffer sb = new StringBuffer("");
//        try {
//            URL url = new URL("http://upload.chaojiying.net/Upload/Processing.php");
//            connection = (HttpURLConnection) url.openConnection();
//            connection.setDoOutput(true);
//            connection.setDoInput(true);
//            connection.setRequestMethod("POST");
//            connection.setUseCaches(false);
//            connection.setInstanceFollowRedirects(true);
//            connection.setRequestProperty("Accept", "*/*");
//            connection.connect();
//
//            DataOutputStream writer = new DataOutputStream(
//                    connection.getOutputStream());
//
//            writer.writeBytes(paramUrl);
//            writer.flush();
//            writer.close();
//
//            BufferedReader reader = new BufferedReader(new InputStreamReader(
//                    connection.getInputStream(), "utf-8"));
//            String lines;
//            while ((lines = reader.readLine()) != null) {
//                lines = new String(lines.getBytes());
//                sb.append(lines);
//            }
//
//            reader.close();
//            connection.disconnect();
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        } catch (ProtocolException e) {
//            e.printStackTrace();
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            if (connection != null) {
//                connection.disconnect();
//            }
//        }
//        return sb.toString();
//    }

}
